import React, { useRef, useState, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { Select, Button, Modal, Message, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import moment from 'moment';
import { nanoid } from 'nanoid';
import request from '@/utils/request';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormDigit,
} from '@ant-design/pro-form';
import Track from './components/track';
import { StatisticCard } from '@ant-design/pro-components';
const { Divider } = StatisticCard;

export default (props) => {
  const actionRef = useRef();
  const [isAddVisible, setIsAddVisible] = useState(false);
  const [isEditVisible, setIsEditVisible] = useState(false);
  const [editRecord, setEditRecord] = useState({});

  const [isShowTrack, setIsShowTrack] = useState(false);
  const [status, setStatus] = useState([]);
  const [statusVlueEumn, setStatusVlueEumn] = useState({});
  const [filterStatus, setFilterStatus] = useState('');
  const [countInfo, setCountInfo] = useState({});
  const [projects, setProjects] = useState([]);
  const [currentProject, setCurrentProject] = useState('');

  const colors = ['#000', 'orange', 'blue', '#ccc', 'red', 'purple', 'green', 'yellow', '#1890ff'];

  const getStatusEumn = () => {
    request.post('/project/getAllProjectStatus').then((res) => {
      setStatus(res);
      const obj = {};
      res &&
        res.map((item) => {
          obj[item.value] = {
            text: item.name,
            status: item.value,
          };
        });
      setStatusVlueEumn(obj);
    });
  };

  const getProjectCount = () => {
    request.post('/issue/issueSummary').then((res) => {
      setCountInfo(res);
    });
  };

  const getAllProject = () => {
    request.post('/project/getAllProjects').then((res) => {
      setProjects(res);
    });
  };

  useEffect(() => {
    getStatusEumn();
    getProjectCount();
    getAllProject();
  }, []);

  const onAddFinish = async (values) => {
    const res = await request.post('/issue/saveIssue', {
      data: {
        ...values,
      },
    });

    if (res.success) {
      Message.success('添加成功');
      setIsAddVisible(false);
      getProjectCount();
      actionRef.current.reload();
    } else {
      if (res.message) {
        Message.error(res.message);
      } else {
        Message.error('添加失败');
      }
    }
  };

  const onEditFinish = async (values) => {
    const res = await request.post('/issue/updateIssue', {
      data: {
        id: editRecord.id,
        ...values,
      },
    });

    if (res.success) {
      Message.success('编辑成功');
      setIsEditVisible(false);
      actionRef.current.reload();
    } else {
      if (res.message) {
        Message.error(res.message);
      } else {
        Message.error('编辑失败');
      }
    }
  };

  const handleRemove = (id) => {
    Modal.confirm({
      title: '确认',
      icon: <QuestionCircleOutlined />,
      content: '确认删除问题？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // const hide = message.loading('正在执行...');
        // hide();
        const res = await request.post('/issue/removeIssue', {
          data: {
            id,
          },
        });
        if (res.success) {
          message.success('删除成功！');
        } else {
          message.error('删除失败！');
        }
        actionRef.current.reloadAndRest();
      },
      onCancel: () => {
        // setIsEditVisible(false);
      },
    });
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '项目',
      dataIndex: 'projectId',
      key: 'projectId',
      hideInTable: true,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        return (
          <Select
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            allowClear
            onChange={(e) => {
              setCurrentProject(e);
            }}
            value={currentProject}
            options={projects.map((item) => {
              return {
                label: item.name,
                value: item.id,
              };
            })}
          ></Select>
        );
      },
    },
    {
      title: '项目',
      dataIndex: 'projectId',
      key: 'projectId',
      hideInSearch: true,
      render: (text1, record, _, action) => {
        console.log(record);
        console.log(projects);
        const project = projects?.find((item) => item.id == record.projectId);
        return <span>{project?.name}</span>;
      },
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      valueEnum: {
        CRITICAL: { text: '严重' },
        NORMAL: { text: '一般' },
        MINOR: { text: '微小' },
      },
      tip: '严重：直接影响到项目验收、收款，或后续项目拓展; 一般：未产生严重影响; 微小：小功能错误，合同没有要求但是客户需要的小改动',
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      valueEnum: {
        HIGH: { text: '高' },
        MEDIUM: { text: '中' },
        LOW: { text: '低' },
      },
    },
    {
      title: '问题状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: {
        PENDING: { text: '待处理' },
        IN_PROGRESS: { text: '处理中' },
        RESOLVED: { text: '已解决' },
      },
    },
    {
      title: '跟进力度',
      dataIndex: 'followUpStatus',
      key: 'followUpStatus',
      tip: '1天没跟进有提示，有三档提示，默认判断条件是1天（不足）和一周（严重不足），可以在添加记录的时候选择下一次提示时间，到了下一次提示时间提示不足，到了下一次提示时间再过一周提示严重不足',
      valueEnum: {
        0: { text: '正常' },
        1: { text: '不足' },
        2: { text: '严重不足' },
      },
      hideInSearch: true,
    },
    {
      title: '关联客户',
      dataIndex: 'relatedCusts',
      key: 'relatedCusts',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      hideInSearch: true,
      // ellipsis: true,
    },
    {
      title: '持续时间(天)',
      dataIndex: 'durationInDays',
      key: 'durationInDays',
      hideInSearch: true,
    },
    {
      title: '关闭时间',
      dataIndex: 'closeTime',
      key: 'closeTime',
      hideInSearch: true,
    },

    {
      title: '提交人',
      dataIndex: 'submitter',
      key: 'submitter',
      hideInSearch: true,
    },

    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      width: 220,
      render: (text, record, _, action) => [
        <a
          key={nanoid()}
          onClick={() => {
            setEditRecord(record);
            setIsShowTrack(true);
          }}
        >
          跟进
        </a>,
        <a
          key="edit"
          onClick={() => {
            setEditRecord(record);
            setIsEditVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            handleRemove(record.id);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const priorityArr = [
    {
      name: '高',
      value: 'HIGH',
      color: 'red',
    },
    {
      name: '中',
      value: 'MEDIUM',
      color: 'blue',
    },
    {
      name: '低',
      value: 'LOW',
      color: 'gray',
    },
  ];

  const severityArr = [
    {
      name: '严重',
      value: 'CRITICAL',
      color: 'red',
    },
    {
      name: '一般',
      value: 'NORMAL',
      color: 'blue',
    },
    {
      name: '微小',
      value: 'MINOR',
      color: 'gray',
    },
  ];

  const getModalFields = () => {
    return (
      <>
        <ProFormText
          name="title"
          label="标题"
          placeholder="请输入标题"
          rules={[
            {
              required: true,
              message: `请输入标题`,
            },
          ]}
        />
        <ProFormSelect
          name="projectId"
          label="关联项目"
          placeholder={`请选择关联项目`}
          rules={[{ required: true, message: `请选择关联项目` }]}
          options={projects.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          })}
          fieldProps={{ showSearch: true }}
        ></ProFormSelect>
        <ProFormTextArea
          name="desc"
          label="问题描述"
          rules={[{ required: true, message: '请输入项目描述' }]}
        ></ProFormTextArea>
        <ProFormSelect
          name="priority"
          label="优先级"
          placeholder={`请选择优先级`}
          rules={[{ required: true, message: `请选择优先级` }]}
          options={priorityArr.map((item) => {
            return {
              label: item.name,
              value: item.value,
            };
          })}
        ></ProFormSelect>
        <ProFormSelect
          name="severity"
          label="严重程度"
          placeholder={`请选择严重程度`}
          rules={[{ required: true, message: `请选择严重程度` }]}
          options={severityArr.map((item) => {
            return {
              label: item.name,
              value: item.value,
            };
          })}
        >
          {/* <Select listHeight={300}>
            {severityArr.map((option, index) => (
              <Select.Option key={option.value} value={option.value}>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <div
                    style={{
                      marginRight: 10,
                      background: option.color,
                      width: 10,
                      height: 10,
                      borderRadius: '50%',
                      position: 'relative',
                    }}
                  >
                    <div
                      style={{
                        background: '#fff',
                        height: 5,
                        width: 5,
                        borderRadius: '50%',
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%,-50%)',
                      }}
                    ></div>
                  </div>
                  <span>{option.name}</span>
                </div>
              </Select.Option>
            ))}
          </Select> */}
        </ProFormSelect>
      </>
    );
  };

  return (
    <>
      <PageContainer style={{ display: isShowTrack ? 'none' : 'block' }} title={props.route.name}>
        <div
          style={{
            background: '#fff',
            borderBottom: '1px solid #f2f2f2',
            padding: '10px 30px',
            fontWeight: 'bold',
            fontSize: 16,
            marginTop: 30,
          }}
        >
          <span>统计信息</span>
        </div>

        <StatisticCard.Group>
          <StatisticCard
            statistic={{
              title: '待解决问题个数',
              // tip: '帮助文字',
              value: countInfo.pendingCount,
            }}
          />
          <Divider />
          <StatisticCard
            statistic={{
              title: '平均解决时间(天)',
              value: countInfo.avgResolveDays,
            }}
          />
        </StatisticCard.Group>
        <ProTable
          onReset={() => {
            setCurrentProject('');
          }}
          pagination={{
            pageSize: 10,
          }}
          headerTitle="问题管理"
          columns={columns}
          actionRef={actionRef}
          rowSelection={false}
          cardBordered
          request={async (params = {}, sort, filter) => {
            const res = request.post('/issue/list', {
              data: {
                pageNo: params.current,
                pageSize: params.pageSize,
                severity: params.severity,
                priority: params.priority,
                status: params.status,
                title: params.title,
                project: currentProject,
              },
            });
            return res;
          }}
          editable={
            {
              // type: 'multiple',
            }
          }
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'localStorage',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={(e) => setIsAddVisible(true)}
            >
              新建问题
            </Button>,
          ]}
        />
        {/* 新建型号 */}
        <ModalForm
          initialValues={{
            beyond: false,
          }}
          title="新建问题"
          width={500}
          visible={isAddVisible}
          onFinish={onAddFinish}
          onVisibleChange={(visible) => !visible && setIsAddVisible(false)}
          validateTrigger="onBlur"
          layout="horizontal"
          labelCol={{ span: 5 }}
          modalProps={{ destroyOnClose: true }}
        >
          {getModalFields()}
        </ModalForm>
        {/*  编辑型号*/}
        <ModalForm
          initialValues={editRecord}
          title="编辑问题"
          width={500}
          visible={isEditVisible}
          onFinish={onEditFinish}
          onVisibleChange={(visible) => !visible && setIsEditVisible(false)}
          validateTrigger="onBlur"
          layout="horizontal"
          labelCol={{ span: 5 }}
          modalProps={{ destroyOnClose: true }}
        >
          <div>{getModalFields()}</div>
        </ModalForm>
      </PageContainer>
      <div style={{ display: !isShowTrack ? 'none' : 'block' }}>
        <Track
          statusVlueEumn={statusVlueEumn}
          actionRef={actionRef}
          setIsShowTrack={setIsShowTrack}
          data={editRecord}
          projectName={projects?.find((item) => item.id == editRecord.projectId)?.name}
          status={status.map((item) => ({ label: item.name, value: item.value }))}
          priorityArr={priorityArr}
          severityArr={severityArr}
          getProjectCount={getProjectCount}
        ></Track>
      </div>
    </>
  );
};
